package org.example.dbw;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.bson.Document;
import org.example.dbw.ot.EtService;
import org.example.dbw.ot.ParamDic;
import org.example.dbw.po.ConfigPo;
import org.example.dbw.po.ForeignKey;
import org.example.dbw.po.Table;
import org.example.dbw.po.TableColumn;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
import java.util.stream.Collectors;

public class ExportToWord {

    public static void genDbDesigDoc(ConfigPo conf){
        Logger global = Logger.getGlobal();
        global.info("开始连接数据库！");
        EtService etService = new EtService(conf,1);
        // 创建文件夹
        new File(conf.getReportPath() + "er").mkdirs();
        try {
            global.info("开始连获取元数据...");
            Map<String, List<TableColumn>> data = etService.getDbTbcData(conf.getDatabase());// 表名：表体
            List<Table> tables = etService.getTables(conf.getDatabase());         // 表体(列名、类型、注释)
            Map<String, String> tableMap = new HashMap<>();              // 表名:中文名
            //所有约束
            List<ForeignKey> tbForeignKey = etService.getTbForeignKey(conf.getDatabase(),"");
            for (Table table : tables) {
                tableMap.put(table.getTableName(), table.getTableCommont());
            }
            // 构建文档
            genLocalDoc(conf, etService, data, tableMap, tbForeignKey);
            global.info("生成完毕，文件地址:"+conf.getReportPath());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    private static void genLocalDoc(ConfigPo conf, EtService etService, Map<String, List<TableColumn>> data, Map<String, String> tableMap, List<ForeignKey> tbForeignKey) throws IOException {
        XWPFDocument document = new XWPFDocument();
        // 导出标识符
        etService.genFlag(data, tableMap, document);
        // 导出er图
        etService.genErModle(data, tableMap, document, tbForeignKey);
        // 导出 逻辑结构设计
        etService.genLogical(data, tableMap, document);
        // 导出 物理结构设计
        etService.genPhysical(data, tableMap, document);
        // 文档输出
        FileOutputStream out = new FileOutputStream(conf.getReportPath() + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()).toString() + "_" + conf.getDatabase() + ".docx");
        document.write(out);
        out.close();
    }

    public static void genMongoDbDesigDoc(ConfigPo conf) {
        Logger global = Logger.getGlobal();

        try {
            global.info("开始连接数据库！");
            MongoClient client = MongoClients.create(conf.getUrl());
            MongoDatabase database = client.getDatabase(conf.getDatabase());
            global.info("开始连获取元数据...");
            //库内所有集合
            MongoIterable<String> cols = database.listCollectionNames();
            Document query = Document.parse(ParamDic.mgColumns);
            Map<String, List<TableColumn>> data=new HashMap<>();// 表名：表体
            List<Table> tables=new ArrayList<>();// 表体(列名、类型、注释)
            Map<String, String> tableMap = new HashMap<>();// 表名:中文名
            for (String col : cols) {
                tableMap.put(col,"暂无描述");
                Table table = new Table();
                table.setTableCommont("暂无描述");
                table.setTableName(col);
                tables.add(table);
                query.put("aggregate",col);
                Document document = database.runCommand(query);
                AtomicInteger index= new AtomicInteger(1);
                List<TableColumn> collect = document.get("cursor", Document.class).getList("firstBatch", Document.class).stream().map(a -> {
                    TableColumn tableColumn = new TableColumn();
                    String columnName = a.getString("columnName");
                    tableColumn.setIspri("_id".equals(columnName)?"Y":"");
                    tableColumn.setColumnComment("暂无描述");
                    tableColumn.setRownum(String.valueOf(index.get()));
                    tableColumn.setColumnName(columnName);
                    tableColumn.setColumnType(a.getString("columnType"));
                    index.getAndIncrement();
                    return tableColumn;
                }).collect(Collectors.toList());
                data.put(col,collect);
            }
            EtService etService = new EtService(conf,2);
            genLocalDoc(conf, etService, data, tableMap, null);
            global.info("生成完毕，文件地址:"+conf.getReportPath());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
